package com.mall.web.control;

import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ibm.icu.text.SimpleDateFormat;
import com.mall.biz.weixin.WeiXinSendMessBizImpl;
import com.mall.common.util.bit.PropertiesConfigure;
import com.mall.common.util.sms.HuYiSmsUtil;
import com.mall.constant.PropertiesKey;
import com.mall.enums.WeiXinTemplateId;
import com.mall.vo.weixin.Template;
import com.mall.vo.weixin.TemplateParam;
import com.mall.web.util.HttpUtil;
import com.tencent.common.Configure;
import com.tencent.common.RandomStringGenerator;
import com.tencent.common.Signature;
import com.tencent.protocol.jspay.JspayRequest;

@Controller
@RequestMapping("/wxShare/")
public class WeiXinShareController implements InitializingBean {

	private static final Logger log = LoggerFactory.getLogger(WeiXinShareController.class);
	
	/**
	 * 鉴权成功后返回页面地址
	 */
	private static String AUTH_RETURN_URI;
	/**
	 * 获取用户信息
	 */
	public static final String WX_USERINFO_URL = "https://api.weixin.qq.com/cgi-bin/user/info";
	/**
	 * 鉴权请求地址模板   scope=snsapi_base  静默授权
	 * 
	 * 当scope=snsapi_userinfo时，用户手动同意授权获取用户信息(无须关注公众号)
	 * 
	 */
	private static final String REDIRECT_URL_TPL = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=%s&redirect_uri=%s&response_type=code&scope=snsapi_base&state=%s#wechat_redirect";
	/**
	 * 获取access_token接口地址
	 */
	private static final String ACCESS_TOKEN_API_URL = "https://api.weixin.qq.com/sns/oauth2/access_token";
//	/**
//	 * 公众号发送模板消息
//	 */
//	
//	private static final  String requestUrl="https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=ACCESS_TOKEN";  
	
	@Autowired
	private PropertiesConfigure propertiesConfigure;
	@Autowired
	private WeiXinSendMessBizImpl weiXinSendMessBiz;
	@Autowired
	private HuYiSmsUtil huYiSmsUtil;

	@RequestMapping("index")
	public String index(HttpServletRequest request, HttpServletResponse response, ModelMap modelMap) {

		log.info("开始获取access_token");
		String accessTokenResponseJsonStr = HttpUtil.sendGet("https://api.weixin.qq.com/cgi-bin/token", String.format(
				"grant_type=client_credential&appid=%s&secret=%s", Configure.getAppid(), Configure.getAppSecret()));
		log.info("获取access_token请求结果：{}", accessTokenResponseJsonStr);
		JSONObject accessTokenResponseJsonObj = JSON.parseObject(accessTokenResponseJsonStr);
		String access_token = accessTokenResponseJsonObj.getString("access_token");
		if (StringUtils.isBlank(access_token)) {
			log.error("获取access_token失败！");
			return null;
		}

		log.info("开始获取ticket");
		String ticketresponseJsonStr = HttpUtil.sendGet("https://api.weixin.qq.com/cgi-bin/ticket/getticket",
				String.format("access_token=%s&type=jsapi", access_token));
		log.info("获取ticket结果：{}", ticketresponseJsonStr);
		JSONObject ticketresponseJsonObj = JSON.parseObject(ticketresponseJsonStr);
		String ticket = ticketresponseJsonObj.getString("ticket");

		Map<String, Object> jsWxConfig = new HashMap<String, Object>();
		jsWxConfig.put("noncestr", RandomStringGenerator.getRandomStringByLength(32));
		jsWxConfig.put("jsapi_ticket", ticket);
		jsWxConfig.put("timestamp", String.valueOf(System.currentTimeMillis() / 1000));
		jsWxConfig.put("url", propertiesConfigure.getProperties(PropertiesKey.httpbeginurl) + "/wxShare/index.htm");
		String configSign = Signature.getSignForJsConfig(jsWxConfig);
		jsWxConfig.put("appId", Configure.getAppid());
		jsWxConfig.put("sign", configSign);

		JspayRequest jspayRequest = new JspayRequest();
		jspayRequest.setTimeStamp(String.valueOf(System.currentTimeMillis() / 1000));
		jspayRequest.setNonceStr(RandomStringGenerator.getRandomStringByLength(32));
		jspayRequest.setAppId(Configure.getAppid());
		jspayRequest.setSignType("MD5");
		String paySign = Signature.getSign(jspayRequest.toMap());
		jspayRequest.setPaySign(paySign);

		modelMap.put("jspayRequest", jspayRequest);
		modelMap.put("jsWxConfig", jsWxConfig);

		return "wxShare/index";
	}

	// @RequestMapping("indexJson")
	// @ResponseBody
	// public ResponseEntity<ModelMap> indexJson(HttpServletRequest request,
	// HttpServletResponse response, ModelMap modelMap) {
	// ResponseEntity<ModelMap> responseEntity = new ResponseEntity<>();
	// log.info("开始获取access_token");
	// String accessTokenResponseJsonStr =
	// HttpUtil.sendGet("https://api.weixin.qq.com/cgi-bin/token",
	// String.format(
	// "grant_type=client_credential&appid=%s&secret=%s", Configure.getAppid(),
	// Configure.getAppSecret()));
	// log.info("获取access_token请求结果：{}", accessTokenResponseJsonStr);
	// JSONObject accessTokenResponseJsonObj =
	// JSON.parseObject(accessTokenResponseJsonStr);
	// String access_token =
	// accessTokenResponseJsonObj.getString("access_token");
	// if (StringUtils.isBlank(access_token)) {
	// log.error("获取access_token失败！");
	// responseEntity.initErrorResponseEntity(null, "error");
	// return null;
	// }
	//
	// log.info("开始获取ticket");
	// String ticketresponseJsonStr =
	// HttpUtil.sendGet("https://api.weixin.qq.com/cgi-bin/ticket/getticket",
	// String.format("access_token=%s&type=jsapi", access_token));
	// log.info("获取ticket结果：{}", ticketresponseJsonStr);
	// JSONObject ticketresponseJsonObj =
	// JSON.parseObject(ticketresponseJsonStr);
	// String ticket = ticketresponseJsonObj.getString("ticket");
	//
	// Map<String, Object> jsWxConfig = new HashMap<String, Object>();
	// jsWxConfig.put("noncestr",
	// RandomStringGenerator.getRandomStringByLength(32));
	// jsWxConfig.put("jsapi_ticket", ticket);
	// jsWxConfig.put("timestamp", String.valueOf(System.currentTimeMillis() /
	// 1000));
	// jsWxConfig.put("url",
	// propertiesConfigure.getProperties(PropertiesKey.httpbeginurl)
	// + "/wxShare/index.htm");
	// String configSign = Signature.getSignForJsConfig(jsWxConfig);
	// jsWxConfig.put("appId", Configure.getAppid());
	// jsWxConfig.put("sign", configSign);
	//
	// JspayRequest jspayRequest = new JspayRequest();
	// jspayRequest.setTimeStamp(String.valueOf(System.currentTimeMillis() /
	// 1000));
	// jspayRequest.setNonceStr(RandomStringGenerator.getRandomStringByLength(32));
	// jspayRequest.setAppId(Configure.getAppid());
	// jspayRequest.setSignType("MD5");
	// String paySign = Signature.getSign(jspayRequest.toMap());
	// jspayRequest.setPaySign(paySign);
	//
	// modelMap.put("jspayRequest", jspayRequest);
	// modelMap.put("jsWxConfig", jsWxConfig);
	//
	// responseEntity.initSuccResponseEntity(modelMap, "success");
	// return responseEntity;
	//
	// }
	//

	@RequestMapping("test")
	public String test(HttpServletRequest request, HttpServletResponse response, ModelMap modelMap) {

		return "wxShare/test";
	}

	@RequestMapping("doPost")
	public String doPost(HttpServletRequest request, HttpServletResponse response, ModelMap modelMap) throws Exception {
		log.error("开始授权请求...");
		String state = String.format("%08d", 123);
		//String AUTH_RETURN_URI = "http://www.zhiwangvip.com/wxShare/authorizeSuccess.htm";

		String redirectUrl = String.format(REDIRECT_URL_TPL, Configure.getAppid(),
				URLEncoder.encode(AUTH_RETURN_URI, "utf-8"), state);
		log.error("redirectTo:{}", redirectUrl);
		return "redirect:" + redirectUrl;
	}

	@RequestMapping("authorizeSuccess")
	public String authorizeSuccess(@RequestParam(required = true) String code, HttpServletRequest request,
			HttpServletResponse response, ModelMap modelMap) {
		log.error("开始获取用户authinfo...");
		// 获取用户openid
		String authResponse = HttpUtil.sendGet(ACCESS_TOKEN_API_URL,
				String.format("appid=%s&secret=%s&code=%s&grant_type=authorization_code", Configure.getAppid(),
						Configure.getAppSecret(), code));
		JSONObject authResponseJson = JSON.parseObject(authResponse);
		log.error("用户authInfo:" + authResponseJson.toString());
		Integer errcode = authResponseJson.getInteger("errcode");
		if (errcode != null && errcode != 0) {
			log.error("请求用户authInfo失败,errcode:{}", errcode);
			return null; // TODO 跳转到error页
		}

		String openId = authResponseJson.getString("openid");

		if (StringUtils.isBlank(openId)) {
			log.error("openid is null");
			return null; // TODO 跳转到error页
		}
		return "redirect:/wxShare/userInfo.htm?openId=" + openId;
	}

	@RequestMapping("userInfo")
	public String userInfo(@RequestParam(required = true) String openId, HttpServletRequest request,
			HttpServletResponse response, ModelMap modelMap) {

		log.info("开始获取access_token");
		String accessTokenResponseJsonStr = HttpUtil.sendGet("https://api.weixin.qq.com/cgi-bin/token", String.format(
				"grant_type=client_credential&appid=%s&secret=%s", Configure.getAppid(), Configure.getAppSecret()));
		log.info("获取access_token请求结果：{}", accessTokenResponseJsonStr);
		JSONObject accessTokenResponseJsonObj = JSON.parseObject(accessTokenResponseJsonStr);
		String access_token = accessTokenResponseJsonObj.getString("access_token");
		log.info("开始获取用户个人信息");
		String userRet = HttpUtil.sendGet(WX_USERINFO_URL,
				String.format("lang=zh_CN&access_token=%s&openid=%s", access_token, openId));
		log.info("获取用户信息请求结果：{}", userRet);
		JSONObject userInfoJO = JSON.parseObject(userRet);

		String user_openid = userInfoJO.getString("openid");
		String user_nickname = userInfoJO.getString("nickname");
//		String user_sex = userInfoJO.getString("sex");
//		String user_province = userInfoJO.getString("province");
//		String user_city = userInfoJO.getString("city");
//		String user_country = userInfoJO.getString("country");
		String user_headimgurl = userInfoJO.getString("headimgurl");
//		String unionid = userInfoJO.getString("unionid");
		System.out.println(user_openid);
		System.out.println(user_nickname);
		System.out.println(user_headimgurl);

//		//获取消息模板
//		String requestUrl="https://api.weixin.qq.com/cgi-bin/template/get_all_private_template";  
//		String hangye = HttpUtil.sendGet(requestUrl, "access_token="+access_token);
//		JSONObject hangyeJO = JSON.parseObject(hangye);
//		System.out.println(hangyeJO);
//		List<Template> temList = JSONObject.parseArray(hangye, Template.class);
//		Template template = null;
//		for (int i = 0; i < temList.size(); i++) {
//			template = temList.get(i);
//			List<TemplateParam> templateParamList = template.getTemplateParamList();
//			System.out.println(templateParamList);
//		}
		SimpleDateFormat sdf=new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");  
		Date date=new Date();  
		String str=sdf.format(date);  
		/*设置发送模板基本信息 */
		Template template=new Template();  
		template.setTemplateId(WeiXinTemplateId.SIGN.getTemplateId());  
		template.setTopColor(WeiXinTemplateId.SIGN.getColor());  
		template.setToUser(openId);  
		template.setUrl("");  
		/*set data*/
		List<TemplateParam> paras=new ArrayList<TemplateParam>();  
		paras.add(new TemplateParam("first","恭喜您签到成功","#FF3333"));  
		paras.add(new TemplateParam("keyword1","每天坚持锻炼身体","#0044BB"));  //这里的keyword1必须与微信公众号模板参数相同
		paras.add(new TemplateParam("keyword2","84372104","#0044BB"));  
		paras.add(new TemplateParam("keyword3",str,"#0044BB")); 
		paras.add(new TemplateParam("remark","请根据活动介绍，参与本次活动，如有疑问请咨询：400-8888-888","#AAAAAA"));  
		          
		template.setTemplateParamList(paras);  
		          
		boolean result= this.weiXinSendMessBiz.sendTemplateMsg(access_token,template); //判断模板信息是否发送成功
		
		if(result){
			log.info("send mess success");
		}else{
			System.out.println("失败了！！！");
		}
		
	
		
		
		return "wxShare/userInfo";
	}
	@RequestMapping("smsTest")
	public void smsTest(){
		String phone = "15658022368";
		String content = "898945654";
		content = "[城市助手]亲爱的店家，" + content + "下单了，请到后台查看！";
		Boolean result = huYiSmsUtil.sendSms(phone,content);
		System.out.println(result);
	}
	
	
	

	@Override
	public void afterPropertiesSet() throws Exception {
		AUTH_RETURN_URI =  propertiesConfigure.getProperties(PropertiesKey.httpbeginurl) + "/wxShare/authorizeSuccess.htm";
		
	}
	
	
}
